// 全局变量
let currentPage = 1;
let rowsPerPage = 12;
let totalPages = 0;
let totalCheckins = 0;
let currentCheckins = [];

// API接口配置
const API = {
    // 获取打卡列表
    getCheckins: (params) => {
        return $.ajax({
            url: '/checking/list',
            type: 'GET',
            data: params,
            dataType: 'json'
        });
    },

    // 搜索打卡记录
    searchCheckins: (params) => {
        return $.ajax({
            url: '/checking/list',
            type: 'POST',
            data: params,
            // contentType: 'application/json',
            dataType: 'json'
        });
    },

    // 查看打卡详情
    getCheckinDetail: (id) => {
        return $.ajax({
            url: `checking/get/${id}`,
            type: 'GET',
            dataType: 'json'
        });
    },

    // 编辑打卡记录
    updateCheckin: (data) => {
        return $.ajax({
            url: '/api/checkins/update',
            type: 'PUT',
            data: JSON.stringify(data),
            contentType: 'application/json',
            dataType: 'json'
        });
    },

    // 删除打卡记录
    deleteCheckin: (id) => {
        return $.ajax({
            url: `/checking/delete/${id}`,
            type: 'DELETE',
            dataType: 'json'
        });
    }
};

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    loadCheckins();
    bindEvents();
});

// 加载打卡数据
function loadCheckins() {
    showLoader();

    const params = {
        page: currentPage,
        pageSize: rowsPerPage,
        username: document.getElementById('userIdFilter').value,
        shopname: document.getElementById('shopIdFilter').value,
        scriptname: document.getElementById('scriptIdFilter').value,
        isShared: document.getElementById('sharedFilter').value
    };

    API.getCheckins(params)
        .then(response => {
            if (response.code === 200) {
                currentCheckins = response.data.rows || [];
                totalCheckins = response.data.total || 0;
                totalPages = Math.ceil(totalCheckins / rowsPerPage);
                renderCheckinCards(currentCheckins);
                renderPagination();
            } else {
                showError('加载打卡数据失败: ' + (response.message || '未知错误'));
            }
        })
}

// 搜索打卡记录
function searchCheckins() {
    showLoader();

    const searchParams = {
        page: 1,
        pageSize: rowsPerPage,
        username: document.getElementById('userIdFilter').value,
        shopname: document.getElementById('shopIdFilter').value,
        scriptname: document.getElementById('scriptIdFilter').value,
        isShared: document.getElementById('sharedFilter').value
    };
    console.log(searchParams)
    API.searchCheckins(searchParams)
        .then(response => {
            if (response.code === 200) {
                currentCheckins = response.data.rows || [];
                totalCheckins = response.data.total || 0;
                totalPages = Math.ceil(totalCheckins / rowsPerPage);
                currentPage = 1;
                renderCheckinCards(currentCheckins);
                renderPagination();
            } else {
                showError('搜索失败: ' + (response.message || '未知错误'));
            }
        })
        .catch(error => {
            console.error('搜索请求失败:', error);
            showError('搜索失败: ' + (error.statusText || '未知错误'));
        })
        .always(() => {
            hideLoader();
        });
}

// 渲染打卡卡片
function renderCheckinCards(checkins) {
    const container = document.getElementById('cardsContainer');

    if (checkins.length === 0) {
        container.innerHTML = `
            <div class="empty-state">
                <i class="bi bi-inbox"></i>
                <h3>暂无打卡数据</h3>
                <p>暂时没有找到符合条件的打卡记录</p>
            </div>
        `;
        return;
    }

    container.innerHTML = checkins.map(checkin => {
        const imgs = JSON.parse(checkin.imgsUrls || '[]');
        const userInitial = checkin.username ? checkin.username.charAt(0) : 'U';

        return `
            <div class="checkin-card" data-id="${checkin.id}">
                <div class="card-header">
                    <div class="card-id">打卡记录 #${checkin.scriptname}</div>
                        <span class="card-status ${checkin.isShared ? 'status-shared' : 'status-private'}">
                        ${checkin.isShared ? '已分享' : '未分享'}
                    </span>
                </div>

                <div class="card-body">
                    <div class="user-info">
                        <div class="user-avatar" style="overflow: hidden"><img width="100%" height="100%" src="${checkin.icon}"></div>
                        <div class="user-details">
                            <h3>${checkin.username || '未知用户'}</h3>
                            <p>店铺名称: ${checkin.shopname}</p>
                        </div>
                    </div>

                    <div class="card-content">
                        <div class="content-text">${checkin.context || '暂无内容描述'}</div>
                    </div>

                    ${imgs.length > 0 ? `
                    <div class="carousel-container" data-carousel="${checkin.id}">
                        <div class="carousel-slides" id="carousel-${checkin.id}">
                            ${imgs.map((img, index) => `
                                <div class="carousel-slide">
                                    <img src="${img}" alt="打卡图片 ${index + 1}" onerror="this.src=''">
                                </div>
                            `).join('')}
                        </div>

                        ${imgs.length > 1 ? `
                        <div class="carousel-controls">
                            <button class="carousel-btn prev-btn" data-carousel="${checkin.id}">
                                <i class="bi bi-chevron-left"></i>
                            </button>
                            <button class="carousel-btn next-btn" data-carousel="${checkin.id}">
                                <i class="bi bi-chevron-right"></i>
                            </button>
                        </div>

                        <div class="carousel-indicators">
                            ${imgs.map((_, index) => `
                                <div class="indicator ${index === 0 ? 'active' : ''}"
                                     data-carousel="${checkin.id}" data-index="${index}"></div>
                            `).join('')}
                        </div>
                        ` : ''}
                    </div>
                    ` : `
                    <div class="no-images">
                        <i class="bi bi-image"></i>
                        <span style="margin-left: 8px;">暂无图片</span>
                    </div>
                    `}

                    <div class="card-stats">
                        <div class="stat-item likes">
                            <i class="bi bi-heart-fill stat-icon"></i>
                            <div>
                                <div class="stat-value">${checkin.likes || 0}</div>
                                <div class="stat-label">点赞</div>
                            </div>
                        </div>
                        <div class="stat-item reviews">
                            <i class="bi bi-chat-dots-fill stat-icon"></i>
                            <div>
                                <div class="stat-value">${checkin.reviews || 0}</div>
                                <div class="stat-label">评论</div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card-footer">
                    <div class="card-date">
                        <i class="bi bi-clock"></i>
                        ${formatDate(checkin.createdAt)}
                    </div>
                    <div class="card-actions">
                        <button class="btn-action btn-view" data-id="${checkin.id}">
                            <i class="bi bi-eye"></i> 查看
                        </button>
                        <button class="btn-action btn-delete" data-id="${checkin.id}">
                            <i class="bi bi-trash"></i> 删除
                        </button>
                    </div>
                </div>
            </div>
        `;
    }).join('');

    // 初始化轮播图
    initCarousels();
}

// 渲染分页
function renderPagination() {
    const pageNumbers = document.getElementById('pageNumbers');
    pageNumbers.innerHTML = '';

    // 上一页按钮状态
    const prevBtn = document.getElementById('prevPage');
    prevBtn.disabled = currentPage === 1;
    prevBtn.classList.toggle('disabled', currentPage === 1);

    // 下一页按钮状态
    const nextBtn = document.getElementById('nextPage');
    nextBtn.disabled = currentPage === totalPages || totalPages === 0;
    nextBtn.classList.toggle('disabled', currentPage === totalPages || totalPages === 0);

    // 如果没有数据或只有一页，显示单个页码
    if (totalPages <= 1) {
        if (totalPages === 1) {
            const pageBtn = document.createElement('button');
            pageBtn.className = 'page-btn active';
            pageBtn.textContent = '1';
            pageBtn.addEventListener('click', () => goToPage(1));
            pageNumbers.appendChild(pageBtn);
        }
        return;
    }

    // 多页情况下的页码显示逻辑
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    // 调整起始页，确保显示足够的页码
    if (endPage - startPage + 1 < maxVisiblePages) {
        startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    // 显示第一页和省略号（如果需要）
    if (startPage > 1) {
        const firstPage = document.createElement('button');
        firstPage.className = 'page-btn';
        firstPage.textContent = '1';
        firstPage.addEventListener('click', () => goToPage(1));
        pageNumbers.appendChild(firstPage);

        if (startPage > 2) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.style.padding = '0 10px';
            ellipsis.style.color = '#6c757d';
            pageNumbers.appendChild(ellipsis);
        }
    }

    // 显示中间页码
    for (let i = startPage; i <= endPage; i++) {
        const pageBtn = document.createElement('button');
        pageBtn.className = `page-btn ${i === currentPage ? 'active' : ''}`;
        pageBtn.textContent = i;
        pageBtn.addEventListener('click', () => goToPage(i));
        pageNumbers.appendChild(pageBtn);
    }

    // 显示最后一页和省略号（如果需要）
    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            const ellipsis = document.createElement('span');
            ellipsis.textContent = '...';
            ellipsis.style.padding = '0 10px';
            ellipsis.style.color = '#6c757d';
            pageNumbers.appendChild(ellipsis);
        }

        const lastPage = document.createElement('button');
        lastPage.className = 'page-btn';
        lastPage.textContent = totalPages;
        lastPage.addEventListener('click', () => goToPage(totalPages));
        pageNumbers.appendChild(lastPage);
    }
}

// 跳转到指定页码
function goToPage(page) {
    if (page < 1 || page > totalPages) return;
    currentPage = page;
    loadCheckins();
}

// 查看打卡详情
function viewCheckinDetail(id) {
    showLoader();

    API.getCheckinDetail(id)
        .then(response => {
            if (response.code === 200) {
                const checkin = response.data;
                showCheckinDetailModal(checkin);
            } else {
                showError('获取详情失败: ' + (response.message || '未知错误'));
            }
        })
}

// 显示打卡详情模态框
function showCheckinDetailModal(checkin) {
    const imgs = JSON.parse(checkin.imgsUrls || '[]');

    // 构建详情HTML
    const detailHtml = `
        <div class="detail-section">
            <h4><i class="bi bi-person-circle"></i>用户信息</h4>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="detail-label">用户名称</span>
                    <div class="detail-value">${checkin.username || '未知用户'}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">用户头像</span>
                    <img width="45px" height="45px" src="${checkin.icon || 'N/A'}" style="border-radius: 50%"/>
                </div>
            </div>
        </div>

        <div class="detail-section">
            <h4><i class="bi bi-shop"></i>店铺信息</h4>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="detail-label">店铺名称</span>
                    <div class="detail-value">${checkin.shopname || '未知店铺'}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">店铺图片</span>
                     <img width="45px" height="45px" src="${checkin.shopicon || 'N/A'}" style="border-radius: 50%"/>
                </div>
            </div>
        </div>

        ${checkin.scriptname ? `
        <div class="detail-section">
            <h4><i class="bi bi-journal-text"></i>剧本信息</h4>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="detail-label">剧本名称</span>
                    <div class="detail-value">${checkin.scriptname}</div>
                </div>
                
            </div>
        </div>
        ` : ''}

        <div class="detail-section">
            <h4><i class="bi bi-chat-left-text"></i>打卡内容</h4>
            <div class="detail-content">${checkin.context || '无内容'}</div>
        </div>

        <div class="detail-section">
            <h4><i class="bi bi-image"></i>打卡图片</h4>
            ${imgs.length > 0 ? `
                <div class="images-preview">
                    ${imgs.map((img, index) => `
                        <div class="image-item" onclick="openImage('${img}')">
                            <img src="${img}" alt="打卡图片 ${index + 1}" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex';">
                            <div class="image-placeholder" style="display: none;">
                                <i class="bi bi-image"></i>
                            </div>
                        </div>
                    `).join('')}
                </div>
            ` : `
                <div class="detail-content" style="text-align: center; color: #95a5a6;">
                    <i class="bi bi-image" style="font-size: 24px; margin-bottom: 8px; display: block;"></i>
                    无图片
                </div>
            `}
        </div>

        <div class="detail-section">
            <h4><i class="bi bi-graph-up"></i>统计数据</h4>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="detail-label">点赞数</span>
                    <div class="detail-value">${checkin.likes || 0}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">评论数</span>
                    <div class="detail-value">${checkin.reviews || 0}</div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">分享状态</span>
                    <div class="detail-value">
                        <span class="status-badge ${checkin.isShared ? 'status-shared' : 'status-private'}">
                            <i class="bi ${checkin.isShared ? 'bi-share-fill' : 'bi-lock-fill'}"></i>
                            ${checkin.isShared ? '已分享' : '未分享'}
                        </span>
                    </div>
                </div>
                <div class="detail-item">
                    <span class="detail-label">打卡ID</span>
                    <div class="detail-value">${checkin.id}</div>
                </div>
            </div>
        </div>

        <div class="detail-section">
            <h4><i class="bi bi-clock"></i>时间信息</h4>
            <div class="detail-grid">
                <div class="detail-item">
                    <span class="detail-label">创建时间</span>
                    <div class="detail-value">${formatDate(checkin.createdAt)}</div>
                </div>
                ${checkin.updatedAt && checkin.updatedAt !== checkin.createdAt ? `
                <div class="detail-item">
                    <span class="detail-label">更新时间</span>
                    <div class="detail-value">${formatDate(checkin.updatedAt)}</div>
                </div>
                ` : ''}
            </div>
        </div>
    `;

    // 填充模态框内容
    document.getElementById('modalBody').innerHTML = detailHtml;

    // 显示模态框
    const modal = document.getElementById('detailModal');
    modal.style.display = 'block';

    // 添加关闭事件
    document.getElementById('closeModal').onclick = function() {
        modal.style.display = 'none';
    };

    // 点击模态框外部关闭
    modal.onclick = function(event) {
        if (event.target === modal) {
            modal.style.display = 'none';
        }
    };
}

// 辅助函数：在新窗口打开图片
function openImage(imgUrl) {
    window.open(imgUrl, '_blank');
}

// 辅助函数：格式化日期
function formatDate(dateString) {
    if (!dateString) return 'N/A';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });
}

// 编辑打卡记录
function editCheckin(id) {
    const checkin = currentCheckins.find(c => c.id === id);
    if (!checkin) return;

    // 这里可以打开编辑模态框
    // 由于移除了添加功能，编辑功能也暂时注释
    // openEditModal(checkin);
    alert('编辑功能暂未实现');
}

// 删除打卡记录
function deleteCheckin(id) {
    if (!confirm('确定要删除这条打卡记录吗？此操作不可恢复。')) {
        return;
    }

    showLoader();

    API.deleteCheckin(id)
        .then(response => {
            if (response.code === 200) {
                showSuccess('打卡记录删除成功');
                // 重新加载数据
                loadCheckins();
            } else {
                showError('删除失败: ' + (response.message || '未知错误'));
            }
        })

}

// 初始化轮播图
function initCarousels() {
    document.querySelectorAll('.carousel-container').forEach(container => {
        const carouselId = container.dataset.carousel;
        const slides = document.getElementById(`carousel-${carouselId}`);
        const totalSlides = slides.children.length;
        let currentSlide = 0;

        // 上一张按钮
        container.querySelector('.prev-btn')?.addEventListener('click', () => {
            currentSlide = (currentSlide - 1 + totalSlides) % totalSlides;
            updateCarousel(carouselId, currentSlide);
        });

        // 下一张按钮
        container.querySelector('.next-btn')?.addEventListener('click', () => {
            currentSlide = (currentSlide + 1) % totalSlides;
            updateCarousel(carouselId, currentSlide);
        });

        // 指示器点击
        container.querySelectorAll('.indicator').forEach((indicator, index) => {
            indicator.addEventListener('click', () => {
                currentSlide = index;
                updateCarousel(carouselId, currentSlide);
            });
        });
    });
}

// 更新轮播图显示
function updateCarousel(carouselId, slideIndex) {
    const slides = document.getElementById(`carousel-${carouselId}`);
    const indicators = document.querySelectorAll(`.indicator[data-carousel="${carouselId}"]`);

    slides.style.transform = `translateX(-${slideIndex * 100}%)`;

    indicators.forEach((indicator, index) => {
        indicator.classList.toggle('active', index === slideIndex);
    });
}

// 格式化日期
function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
}

// 显示加载动画
function showLoader() {
    const loader = document.getElementById('compact-loader');
    if (loader) loader.style.display = 'flex';
}

// 隐藏加载动画
function hideLoader() {
    const loader = document.getElementById('compact-loader');
    if (loader) loader.style.display = 'none';
}

// 显示成功消息
// 显示成功提示
function showSuccess(message, duration = 5000) {
    const alert = document.getElementById('success-alert');
    const messageElement = document.getElementById('success-message');

    // 设置消息内容
    messageElement.textContent = message || '操作已成功完成';

    // 显示提示框
    alert.classList.add('show');

    // 添加进度条
    addProgressBar(alert, duration);

    // 自动隐藏
    setTimeout(() => {
        hideSuccessAlert();
    }, duration);
}

// 显示错误提示
function showError(message, duration = 5000) {
    const alert = document.getElementById('error-alert');
    const messageElement = document.getElementById('error-message');

    // 设置消息内容
    messageElement.textContent = message || '操作过程中出现错误';

    // 显示提示框
    alert.classList.add('show');

    // 添加进度条
    addProgressBar(alert, duration);

    // 自动隐藏
    setTimeout(() => {
        hideErrorAlert();
    }, duration);
}

// 隐藏成功提示
function hideSuccessAlert() {
    const alert = document.getElementById('success-alert');
    alert.classList.remove('show');
    removeProgressBar(alert);
}

// 隐藏错误提示
function hideErrorAlert() {
    const alert = document.getElementById('error-alert');
    alert.classList.remove('show');
    removeProgressBar(alert);
}

// 添加进度条
function addProgressBar(alert, duration) {
    removeProgressBar(alert);

    const progressBar = document.createElement('div');
    progressBar.className = 'alert-progress';
    progressBar.style.animationDuration = duration + 'ms';

    alert.querySelector('.alert-content').appendChild(progressBar);
}

// 移除进度条
function removeProgressBar(alert) {
    const existingProgress = alert.querySelector('.alert-progress');
    if (existingProgress) {
        existingProgress.remove();
    }
}

// 点击提示框外部关闭
document.addEventListener('click', function(event) {
    const successAlert = document.getElementById('success-alert');
    const errorAlert = document.getElementById('error-alert');

    if (successAlert.classList.contains('show') &&
        !event.target.closest('#success-alert')) {
        hideSuccessAlert();
    }

    if (errorAlert.classList.contains('show') &&
        !event.target.closest('#error-alert')) {
        hideErrorAlert();
    }
});
// 绑定事件
function bindEvents() {
    // 搜索按钮
    document.getElementById('searchBtn').addEventListener('click', searchCheckins);

    // 分页按钮
    document.getElementById('prevPage').addEventListener('click', () => {
        if (currentPage > 1) goToPage(currentPage - 1);
    });

    document.getElementById('nextPage').addEventListener('click', () => {
        if (currentPage < totalPages) goToPage(currentPage + 1);
    });

    // 每页显示数量变化
    document.getElementById('pageSize').addEventListener('change', (e) => {
        rowsPerPage = parseInt(e.target.value);
        currentPage = 1;
        loadCheckins();
    });

    // 输入框回车搜索
    [document.getElementById('userIdFilter'),
        document.getElementById('shopIdFilter'),
        document.getElementById('scriptIdFilter')].forEach(input => {
        input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                searchCheckins();
            }
        });
    });

    // 卡片操作按钮事件委托
    document.getElementById('cardsContainer').addEventListener('click', (e) => {
        const target = e.target.closest('.btn-action');
        if (!target) return;

        const id = parseInt(target.getAttribute('data-id'));

        if (target.classList.contains('btn-view')) {
            viewCheckinDetail(id);
        } else if (target.classList.contains('btn-edit')) {
            editCheckin(id);
        } else if (target.classList.contains('btn-delete')) {
            deleteCheckin(id);
        }
    });

    // 提示框关闭按钮
    document.querySelectorAll('.alert-close').forEach(btn => {
        btn.addEventListener('click', (e) => {
            e.target.closest('.alert').style.display = 'none';
        });
    });
}